import store from '@/store/store';

// ajax计数
let ajaxCount = 0;
// loading消失的延迟
let loadingTimer = null;

// loading开始计数
export const loadingStart = config => {
  if (!config.hasOwnProperty('loading') || config['loading']) {
    ajaxCount++;
    if (loadingTimer) clearTimeout(loadingTimer);
    store.state.loadingShow = true
  }
};

/**
 * loading计数结束
 * @param {object} config ajax配置
 * @param {boolean} isEndNow 是否立即结束loading, 正常有500ms延迟才关闭
 * */
export const loadingEnd = (config, isEndNow) => {
  if (!config.hasOwnProperty('loading') || config['loading']) {
    ajaxCount--;
    if (ajaxCount === 0) {
      if (isEndNow) {
        store.state.loadingShow = false;
        loadingTimer = null;
      } else {
        loadingTimer = setTimeout(() => {
          store.state.loadingShow = false
          loadingTimer = null;
        }, 300);
      }
    }
  }
};